package com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.repository.HddcHorizontaldeformationNativeRepository;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.repository.HddcHorizontaldeformationRepository;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.repository.entity.HddcHorizontaldeformationEntity;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.service.HddcHorizontaldeformationService;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.viewobjects.HddcHorizontaldeformationPageVO;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.viewobjects.HddcHorizontaldeformationQueryParams;
import com.css.zfzx.sjcj.modules.hddcHorizontalDeformation.viewobjects.HddcHorizontaldeformationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 水平形变-点管理
 * @author zyb
 * @date 2020-11-26
 */
@Service
public class HddcHorizontaldeformationServiceImpl implements HddcHorizontaldeformationService {

    private final HddcHorizontaldeformationRepository hddcHorizontaldeformationRepository;
    private final HddcHorizontaldeformationNativeRepository hddcHorizontaldeformationNativeRepository;
    private final HorizontalDeformationPointManaExcelVerifyHandle horizontalDeformationPointManaExcelVerifyHandle;

    @Autowired
    public HddcHorizontaldeformationServiceImpl(HddcHorizontaldeformationRepository hddcHorizontaldeformationRepository,
                                                HddcHorizontaldeformationNativeRepository hddcHorizontaldeformationNativeRepository,
                                                HorizontalDeformationPointManaExcelVerifyHandle horizontalDeformationPointManaExcelVerifyHandle) {
        this.hddcHorizontaldeformationRepository = hddcHorizontaldeformationRepository;
        this.hddcHorizontaldeformationNativeRepository = hddcHorizontaldeformationNativeRepository;
        this.horizontalDeformationPointManaExcelVerifyHandle = horizontalDeformationPointManaExcelVerifyHandle;
    }

    @Override
    public JSONObject queryHddcHorizontaldeformations(HddcHorizontaldeformationQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcHorizontaldeformationPageVO> hddcHorizontaldeformationPage = this.hddcHorizontaldeformationNativeRepository.queryHddcHorizontaldeformations(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcHorizontaldeformationPage);
    }


    @Override
    public HddcHorizontaldeformationEntity getHddcHorizontaldeformation(String id) {
        return this.hddcHorizontaldeformationRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcHorizontaldeformationEntity saveHddcHorizontaldeformation(HddcHorizontaldeformationEntity hddcHorizontaldeformation) {
        String uuid = UUIDGenerator.getUUID();
        hddcHorizontaldeformation.setUuid(uuid);
        hddcHorizontaldeformation.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcHorizontaldeformation.setCreateTime(now);
        hddcHorizontaldeformation.setUpdateTime(now);
        hddcHorizontaldeformation.setIsValid(PlatformConstants.Y);
        hddcHorizontaldeformation.setQualityinspectionStatus(PlatformConstants.N);
        hddcHorizontaldeformation.setExtends10(PlatformConstants.Y);
        this.hddcHorizontaldeformationRepository.save(hddcHorizontaldeformation);
        return hddcHorizontaldeformation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcHorizontaldeformationEntity updateHddcHorizontaldeformation(HddcHorizontaldeformationEntity hddcHorizontaldeformation) {
        HddcHorizontaldeformationEntity entity = hddcHorizontaldeformationRepository.findById(hddcHorizontaldeformation.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcHorizontaldeformation);
        hddcHorizontaldeformation.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcHorizontaldeformation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcHorizontaldeformationRepository.save(hddcHorizontaldeformation);
        return hddcHorizontaldeformation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcHorizontaldeformations(List<String> ids) {
        List<HddcHorizontaldeformationEntity> hddcHorizontaldeformationList = this.hddcHorizontaldeformationRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcHorizontaldeformationList) && hddcHorizontaldeformationList.size() > 0) {
            for(HddcHorizontaldeformationEntity hddcHorizontaldeformation : hddcHorizontaldeformationList) {
                hddcHorizontaldeformation.setIsValid("0");
                hddcHorizontaldeformation.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcHorizontaldeformation.setUpdateTime(new Date());
                this.hddcHorizontaldeformationRepository.save(hddcHorizontaldeformation);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcHorizontaldeformationQueryParams queryParams, HttpServletResponse response) {
        List<HddcHorizontaldeformationEntity> yhDisasterEntities = hddcHorizontaldeformationNativeRepository.exportYhDisasters(queryParams);
        List<HddcHorizontaldeformationVO> list=new ArrayList<>();
        for (HddcHorizontaldeformationEntity entity:yhDisasterEntities) {
            HddcHorizontaldeformationVO yhDisasterVO=new HddcHorizontaldeformationVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"水平形变-点","水平形变-点",HddcHorizontaldeformationVO.class,"水平形变-点.xls",response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(horizontalDeformationPointManaExcelVerifyHandle);
            // 获取到Excel数据
            ExcelImportResult<HddcHorizontaldeformationVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcHorizontaldeformationVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcHorizontaldeformationVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcHorizontaldeformationVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     */
    public void saveDisasterList(List<HddcHorizontaldeformationVO> list) {
        for (HddcHorizontaldeformationVO hddcHorizontaldeformationVO : list) {
            HddcHorizontaldeformationEntity yhDisasterEntity = new HddcHorizontaldeformationEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcHorizontaldeformationVO, yhDisasterEntity);
            saveHddcHorizontaldeformation(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcHorizontaldeformationEntity> hddcHorizontaldeformationList = this.hddcHorizontaldeformationRepository.queryHddcHorizontaldeformationsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcHorizontaldeformationList) && hddcHorizontaldeformationList.size() > 0) {
            for(HddcHorizontaldeformationEntity hddcHorizontaldeformation : hddcHorizontaldeformationList) {
                hddcHorizontaldeformation.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcHorizontaldeformation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcHorizontaldeformation.setIsValid("0");
                this.hddcHorizontaldeformationRepository.save(hddcHorizontaldeformation);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcHorizontaldeformationEntity> hddcHorizontaldeformationList = this.hddcHorizontaldeformationRepository.queryHddcHorizontaldeformationsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcHorizontaldeformationList) && hddcHorizontaldeformationList.size() > 0) {
            for(HddcHorizontaldeformationEntity hddcHorizontaldeformation : hddcHorizontaldeformationList) {
                hddcHorizontaldeformation.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcHorizontaldeformation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcHorizontaldeformation.setIsValid("0");
                this.hddcHorizontaldeformationRepository.save(hddcHorizontaldeformation);
            }
        }
    }
}
